const asyncValidate = require('async-validator')

const schema = {}

module.exports = {
  async isLogin() {
    if (!this.user || !this.user._id) {
      this.throw(401, 'not login', '请登陆后再操作')
    }
  },
  async validateId() {
    if (!this.params.id || this.params.id.length !== 24) {
      this.throw(422, 'not login', 'ID 不正确')
    }
  },
  uuid: require('node-uuid'),
  async isAdmin() {
    if (!this.user || !this.user._id) {
      this.throw(401, 'not login', '请登陆后再操作')
    }
    if (!this.user || !this.user.isAdmin) {
      this.throw(403, 'not login', '无权操作')
    }
  },
  async safeLoader(keys) {
    const data = {}
    keys.split(',').forEach((key) => {
      if (this.request.body[key] !== undefined) {
        data[key] = this.request.body[key]
      }
    })
    return data
  },
  async validate(rules, model, attributes) {
    // 获取当前的校验模型
    if (typeof rules === 'string') {
      rules = schema[rules]
    }
    if (!rules) {
      throw new Error('校验模型不存在')
    }
    if (typeof model === 'string') {
      attributes = model
    }
    // 校验对象空则为 body
    model = model || this.request.body
    // 删除或选取某些值
    if (attributes) {
      if (attributes.includes('-')) { // 只删除
        attributes.split(',').forEach((key) => {
          if (key.startsWith('-')) {
            delete model[key.replace('-', '')]
          }
        })
      } else { // 只选取
        attributes = attributes.split(',')
        Object.keys(model).forEach((key) => {
          if (!attributes.includes(key)) {
            delete model[key]
          }
        })
      }
    }
    // 选取需要验证的 key 验证
    const _rules = {}
    Object.keys(model).forEach((key) => {
      if (rules[key]) {
        _rules[key] = rules[key]
      }
    })
    // 验证
    return new Promise((resolve) => {
      new asyncValidate(_rules).validate(model, (errors, fields) => {
        if (errors) {
          this.throw(422, 'not validate', { message: errors })
        }
        resolve(model)
      })
    })
  },
}